package com.atguigu.controller;


import com.atguigu.client.CartFeignClient;
import com.atguigu.client.UserFeignClient;
import com.atguigu.entity.CartInfo;
import com.atguigu.entity.OrderDetail;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.UserAddress;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderInfoService;
import com.atguigu.util.AuthContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 订单表 前端控制器
 * </p>
 *
 * @author
 * @since 2022-09-12
 */
@RestController
@RequestMapping("/order")
public class OrderInfoController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderInfoService orderInfoService;

    //订单列表查询
    @GetMapping("/{pageNo}/{pageSize}")
    public RetVal getOrderPageList(@PathVariable Long pageNo,@PathVariable Long pageSize){
        Page<OrderInfo> page = new Page<>(pageNo, pageSize);
        orderInfoService.page(page,null);
        return RetVal.ok(page);
    }

    //1.订单的确认信息
    @GetMapping("confirm")
    public RetVal confirm(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //a.拿到收货人的地址信息 从shop-user中拿
        List<UserAddress> userAddressList = userFeignClient.getUserAddressByUserId(userId);
        //b.用户勾选的商品信息 从shop-cart中拿
        List<CartInfo> selectedCartInfoList = cartFeignClient.getSelectedCartInfo(userId);
        BigDecimal totalMoney = new BigDecimal(0);
        int totalNum = 0;
        List<OrderDetail> orderDetailList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(selectedCartInfoList)) {
            for (CartInfo cartInfo : selectedCartInfoList) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setSkuNum(cartInfo.getSkuNum() + "");
                orderDetail.setOrderPrice(cartInfo.getCartPrice());
                //订单总金额
                totalMoney = totalMoney.add(cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum())));
                //商品的总数量
                totalNum += cartInfo.getSkuNum();
                orderDetailList.add(orderDetail);
            }
        }
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("userAddressList", userAddressList);
        retMap.put("detailArrayList", orderDetailList);
        retMap.put("totalMoney", totalMoney);
        retMap.put("totalNum", totalNum);
        //生成一个流水号给页面和redis
        String tradeNo = orderInfoService.generateTradeNo(userId);
        retMap.put("tradeNo", tradeNo);
        return RetVal.ok(retMap);
    }

    //2.提交订单信息
    @PostMapping("submitOrder")
    public RetVal submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //获取请求参数里的流水号
        String tradeNoUI = request.getParameter("tradeNo");
        //需要从redis里取出一份进行对比
        boolean flag = orderInfoService.checkTradeNo(tradeNoUI, userId);
        if (!flag) {
            return RetVal.fail().message("不能重复提交订单");
        }
        //验证商品的库存和价格
        String warningMessage = orderInfoService.checkStockAndPrice(orderInfo);
        if (!StringUtils.isEmpty(warningMessage)) {
            return RetVal.fail().message(warningMessage);
        }
        //保存订单的基本信息和详情信息
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.saveOrderAndDetail(orderInfo);
        //提交订单后还需要删除流水号
        orderInfoService.deleteTradeNo(userId);
        return RetVal.ok(orderId);
    }

    //3.根据订单id查询订单信息
    @GetMapping("getOrder/{orderId}")
    public OrderInfo getOrder(@PathVariable Long orderId){

        return orderInfoService.getOrder(orderId);
    }

    //4.拆单代码 地址: http://order.gmall.com/order/splitOrder
    @PostMapping("splitOrder")
    public String splitOrder(@RequestParam Long orderId,@RequestParam String wareHouseIdSkuIdMapJson){
        return orderInfoService.splitOrder(orderId,wareHouseIdSkuIdMapJson);
    }

    //5.保存订单及订单详情
    @PostMapping("saveOrderAndDetail")
    public Long saveOrderAndDetail(@RequestBody OrderInfo orderInfo){
        return orderInfoService.saveOrderAndDetail(orderInfo);
    }
}

